// OutpatientChargePanel.java 门诊收费界面
package com.dw.gui.panel.fee;

import com.dw.dao.fee.ChargeDao;
import com.dw.dao.user.PatientDao;
import com.dw.model.fee.ChargeRecord;
import com.dw.model.user.Doctor;
import com.dw.model.invoice.Invoice;
import com.dw.util.UIUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.sql.SQLException;

public class OutpatientChargePanel extends JPanel {
    private final Doctor doctor;
    private JTextField tfPatientId;
    private JLabel lblPatientName;
    private JTextField tfAmount;
    private JComboBox<String> cbChargeType;
    private JComboBox<String> cbPaymentMethod;
    private JTextArea taRemark;

    public OutpatientChargePanel(Doctor doctor) {
        this.doctor = doctor;
        initUI();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);

        // 标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        titlePanel.setBackground(Color.WHITE);
        titlePanel.add(UIUtil.createTitleLabel("门诊收费"));
        titlePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 主表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(Color.WHITE);
        formPanel.setBorder(BorderFactory.createTitledBorder("收费信息"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 患者信息
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(UIUtil.createLabel("患者ID："), gbc);

        gbc.gridx = 1;
        JPanel patientPanel = new JPanel(new BorderLayout(5, 0));
        tfPatientId = UIUtil.createTextField();
        tfPatientId.setPreferredSize(new Dimension(200, 25)); // 固定高度

        JButton btnVerify = UIUtil.createButton("验证");
        btnVerify.addActionListener(this::verifyPatient);
        patientPanel.add(tfPatientId, BorderLayout.CENTER);
        patientPanel.add(btnVerify, BorderLayout.EAST);
        formPanel.add(patientPanel, gbc);

        // 患者姓名行
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(UIUtil.createLabel("患者姓名："), gbc);

        gbc.gridx = 1;
        lblPatientName = UIUtil.createLabel("");
        formPanel.add(lblPatientName, gbc);

        // 收费金额行
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(UIUtil.createLabel("收费金额："), gbc);

        gbc.gridx = 1;
        tfAmount = UIUtil.createTextField();
        tfAmount.setPreferredSize(new Dimension(200, 25));
        formPanel.add(tfAmount, gbc);

        // 收费类型行 (第3行)
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(UIUtil.createLabel("收费类型："), gbc);

        gbc.gridx = 1;
        cbChargeType = UIUtil.createComboBox(new String[]{"普通门诊", "专家门诊", "急诊"});
        cbChargeType.setPreferredSize(new Dimension(200, 25));
        formPanel.add(cbChargeType, gbc);

        // 支付方式行 (第4行)
        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(UIUtil.createLabel("支付方式："), gbc);

        gbc.gridx = 1;
        cbPaymentMethod = UIUtil.createComboBox(new String[]{"现金", "支付宝", "微信支付"});
        cbPaymentMethod.setPreferredSize(new Dimension(200, 25));
        formPanel.add(cbPaymentMethod, gbc);

        // 备注行 (第5行)
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        formPanel.add(UIUtil.createLabel("备注："), gbc);

        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 2;
        taRemark = UIUtil.createTextArea(3, 20);
        JScrollPane remarkScroll = new JScrollPane(taRemark);
        remarkScroll.setPreferredSize(new Dimension(300, 80));
        formPanel.add(remarkScroll, gbc);

        // 操作按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(Color.WHITE);

        JButton btnCharge = UIUtil.createButton("确认收费");
        btnCharge.setPreferredSize(new Dimension(120, 30));
        btnCharge.addActionListener(this::performCharge);

        JButton btnReset = UIUtil.createButton("重置");
        btnReset.setPreferredSize(new Dimension(120, 30));
        btnReset.addActionListener(e -> resetForm());

        buttonPanel.add(btnCharge);
        buttonPanel.add(btnReset);

        // 组装主界面
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(titlePanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);
    }

    private void verifyPatient(ActionEvent e) {
        try {
            int patientId = Integer.parseInt(tfPatientId.getText());
            String patientName = new PatientDao().findById(patientId).getName();
            lblPatientName.setText(patientName);
            tfAmount.requestFocus();
        } catch (NumberFormatException ex) {
            UIUtil.showError(this, "患者ID必须为数字", "输入错误");
        } catch (Exception ex) {
            UIUtil.showError(this, "患者信息验证失败", "数据错误");
        }
    }

    private void performCharge(ActionEvent e) {
        try {
            // 前置验证
            if (tfPatientId.getText().isEmpty() || lblPatientName.getText().isEmpty()) {
                throw new IllegalArgumentException("请先验证患者信息");
            }
            if (tfAmount.getText().isEmpty()) {
                throw new IllegalArgumentException("请输入金额");
            }

            // 创建业务对象
            ChargeRecord record = createChargeRecord();
            Invoice invoice = createInvoice(record);

            // 调用服务类处理事务
            new ChargeDao().createChargeWithInvoice(record, invoice);

            JOptionPane.showMessageDialog(this,
                    "收费成功！\n收费单号：" + record.getChargeNo()
                            + "\n发票号码：" + invoice.getInvoiceNo(),
                    "操作成功",
                    JOptionPane.INFORMATION_MESSAGE);

            resetForm();
        } catch (IllegalArgumentException ex) {
            UIUtil.showError(this, ex.getMessage(), "输入不完整");
        } catch (SQLException ex) {
            UIUtil.showError(this, "数据库操作失败：" + ex.getMessage(), "系统错误");
        } catch (Exception ex) {
            UIUtil.showError(this, "收费失败：" + ex.getMessage(), "系统错误");
        }
    }

    private ChargeRecord createChargeRecord() {
        ChargeRecord record = new ChargeRecord();
        record.setPatientId(Integer.parseInt(tfPatientId.getText()));
        record.setDoctorId(doctor.getId());
        record.setAmount(new BigDecimal(tfAmount.getText()));
        record.setChargeType((String) cbChargeType.getSelectedItem());
        record.setPaymentMethod((String) cbPaymentMethod.getSelectedItem());
        record.setRemark(taRemark.getText());
        record.setChargeNo(generateChargeNo());
        return record;
    }

    private Invoice createInvoice(ChargeRecord record) {
        Invoice invoice = new Invoice();
        invoice.setPatientId(record.getPatientId());
        invoice.setDoctorId(record.getDoctorId());
        invoice.setAmount(record.getAmount());
        invoice.setInvoiceNo(generateInvoiceNo());
        invoice.setStatus("NORMAL");
        return invoice;
    }

    private String generateChargeNo() {
        return "CH" + System.currentTimeMillis();
    }

    private String generateInvoiceNo() {
        return "INV" + System.currentTimeMillis();
    }

    private void resetForm() {
        tfPatientId.setText("");
        lblPatientName.setText("");
        tfAmount.setText("");
        cbChargeType.setSelectedIndex(0);
        cbPaymentMethod.setSelectedIndex(0);
        taRemark.setText("");
    }
}